<template>
  <div class="app-container">
    <el-card style="position: relative">
      <RouterHeader
        title="项目管理日志"
        :time="time"
        :status="status"
      ></RouterHeader>
      <div class="concent">
        <el-form
          :model="form"
          :rules="rules"
          ref="ruleFormRef"
          label-width="140px"
          label-position="right"
        >
          <el-form-item label="记录人" prop="recorder">
            <el-input
              class="input-item"
              v-model="form.recorder"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item label="施工环境" prop="environment">
            <el-input
              class="input-item"
              v-model="form.environment"
              placeholder="请输入"
              :disabled="(route.query.name == '6' || route.query.name == '5') ? true : false"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目实施情况" prop="projectSituation">
            <el-input
              class="input-item"
              type="textarea"
              v-model="form.projectSituation"
              placeholder="请输入"
              show-word-limit
              rows="5"
              :disabled="(route.query.name == '6' || route.query.name == '5') ? true : false"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目管理工作" prop="projectManagement">
            <el-input
              type="textarea"
              class="input-item"
              v-model="form.projectManagement"
              placeholder="请输入"
              show-word-limit
              rows="5"
              :disabled="(route.query.name == '6' || route.query.name == '5') ? true : false"
            ></el-input>
          </el-form-item>

          <el-form-item label="次日工作安排" prop="arrange">
            <el-input
              type="textarea"
              class="input-item"
              v-model="form.arrange"
              placeholder="请输入"
              show-word-limit
              rows="5"
              :disabled="(route.query.name == '6' || route.query.name == '5') ? true : false"
            ></el-input>
          </el-form-item>

          <el-form-item label="其他相关事项" prop="other">
            <el-input
              type="textarea"
              class="input-item"
              v-model="form.other"
              placeholder="请输入"
              show-word-limit
              rows="5"
              :disabled="(route.query.name == '6' || route.query.name == '5') ? true : false"
            ></el-input>
          </el-form-item>

          <el-form-item label="上传附件/图片" prop="projectLogFileList">
            <fileupload
              :modelValue="form.projectLogFileList"
              @update:modelValue="handleModelFileLists"
              :flag="route.query.name != '1'"
            ></fileupload>
          </el-form-item>

          <div v-if="route.query.name !== '1'">
            <div class="concent-title"><h5>项目审批进度</h5></div>
            <el-timeline style="max-width: 600px">
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :color="activity.color"
                :timestamp="activity.updateTime"
              >
                <div style="display: flex; align-items: center">
                  <img :src="url + activity.avatar" class="user-avatar" />
                  <span
                    style="font-size: 14px; font-weight: 500; margin-left: 5px"
                  >
                    {{ activity.username }} ({{
                      activity.checkHisResult === "2" ? "未审核" : "已审核"
                    }})
                    {{
                      activity.zuofei === "0"
                        ? " _作废"
                        : activity.zuofei === "null"
                        ? ""
                        : ""
                    }}
                    :</span
                  >
                  <span
                    style="font-size: 14px; font-weight: 400; margin-left: 5px"
                  >
                    {{ activity.opinion }}</span
                  >
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>

          <div  v-if="route.query.name != '3' && route.query.name != '5'"  class="concent-title" >
            <h5>日志审批流程</h5>
          </div>
          <el-row v-if="route.query.name != '3' && route.query.name != '5'">
            <el-col :span="24">
              <el-form-item label="审批方式">
                <el-radio-group
                  v-model="form.processCheckBo.checkType"
                  :disabled="isDisabled()"
                >
                  <el-radio :label="0">自由审批</el-radio>
                  <el-radio :label="1">逐级审批</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item
                label="审批流程"
                v-if="
                  (route.query.name === '6' &&
                    form.processCheckBo.checkType === 0 &&
                    form.keepCheck === '1') ||
                  (route.query.name !== '6' && form.keepCheck === '1')
                "
              >
                <approver
                  :approverList="form.processCheckBo.checkPeopleIds"
                  @handleChooseapprover="handleChooseapprover"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="抄送"
                v-if="
                  (route.query.name === '6' &&
                    form.processCheckBo.checkType === 0 &&
                    form.keepCheck === '1') ||
                  (route.query.name !== '6' && form.keepCheck === '1')
                "
              >
                <approver
                  :approverList="form.processCheckBo.copyFor"
                  :isCc="true"
                  @handleChooseapprover="handleChooseapproverCc"
                ></approver>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="route.query.name === '3' || route.query.name === '6' || (route.query.name === '5' && route.query.logState == '-1') ">
            <el-col :span="24">
              <el-form-item label="审批意见" prop="projectImplementation">
                <el-input
                  class="input-item"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  maxlength="150"
                  show-word-limit
                  v-model="form.approvalOpinions"
                  placeholder="请输入"
                  :disabled="route.query.name === '5' ? true : false"
                ></el-input>
              </el-form-item>
              <el-form-item label="添加附件/图片" prop="approvalFile">
                <fileupload :modelValue="form.approvalFile"
                  @update:modelValue="handleModelApprovaFileLists"
                  :flag="false" >
                </fileupload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="审批决定"
                prop="projectImplementation"
                v-if="form.processCheckBo.checkType !== 1"
              >
                <el-radio-group
                  v-model="form.keepCheck"
                  class="ml-4"
                  :disabled="route.query.name === '5' ? true : false"
                >
                  <el-radio label="0" size="large">完成审批</el-radio>
                  <el-radio label="1" size="large">继续审批</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-if=" (route.query.name != '5' && route.query.logState == '-1')
          && userStore.rolescode!=15" 
          style="display: flex; justify-content: center">
            <el-button @click="tgsubmitForm(ruleFormRef,'0')">驳回</el-button>
            <el-button type="primary" @click="tgsubmitForm(ruleFormRef,'1')">通过</el-button>
          </div>

          <div v-if="(route.query.name != '5' && route.query.logState != '-1')
          && userStore.rolescode!=15" 
          style="display: flex; justify-content: center">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
          </div>
          <!-- <el-form-item
            style="padding: 20px 0; display: flex; justify-content: center"
          >
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >提交</el-button
            >
          </el-form-item> -->
        </el-form>
      </div>
    </el-card>
    <!-- 选择人员 -->
    <!-- <el-dialog
      title="新增成员"
      v-model="detailsvisible"
      :before-close="handleClose"
      width="60%"
      style="background: #fff; height: 100%; margin-bottom: 20px"
    >
      <selectPeople
        :projectUserDtoList="form.projectUserDtoList"
        @selectTable="selectTable"
        @deleteTable="deleteTable"
        @submitSelectForm="submitSelectForm"
        @handleSelectClose="handleSelectClose"
      ></selectPeople>
    </el-dialog> -->
  </div>
</template>
<script setup>
import { onMounted } from "vue";
import RouterHeader from "@/components/RouterHeader";
import { useRouter, useRoute } from "vue-router";
// import selectPeople from "@/components/selector/selectPeople.vue";
import approver from "@/components/Approve/approver.vue";
// import { reportAdd, dailyDetails } from "@/api/information/daily";
import { statusByProjectApi,updateNoticeApi, noticeDetailsList } from "@/api/notice/index";

import { ElMessageBox, ElMessage } from "element-plus";
import fileupload from "@/components/FileUpload";
import useUserStore from "@/store/modules/user";
import { el } from "element-plus/es/locales.mjs";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

let time = ref("");
let status = ref("");

const ruleFormRef = ref();

const activities = ref([]);
let dataCheckInfo = {};

const form = reactive({
  logId: "",
  recorder: userStore.nickName,
  createTime: "",
  environment: "",
  projectSituation: "",
  projectManagement: "",
  other: "",
  arrange: "",
  projectLogFileList: [], //附件
  processCheckBo: {
    checkPeopleIds: [], //审核人id列表
    copyFor: [], //抄送人id列表
    checkType: 1,
  },
  approvalOpinions: "",
  approvalFile: [],
  keepCheck: "1", //审批决定-完成审批
  projectId:-1//
});

// 取消
const resetForm = (data) => {
  // 2.跳转到对应的tab栏的列表，返回上一步
    router.back();
};

const handleChooseapproverCc = (id) => {
  if (id) {
    form.processCheckBo.copyFor = id;
  }
};

const handleChooseapprover = (id) => {
  if (id) {
    form.processCheckBo.checkPeopleIds = id;
  }
};

const handleModelApprovaFileLists = (val, result, operationType)=>{
  if (operationType === "success") {
    if (result) {
      form.approvalFile = [];
      result.forEach((item)=>{
        form.approvalFile.push(item);
      });
    }
  } 
  else if (operationType === "delete") {
    form.approvalFile.splice(result, 1);
  }
};
  


// 附件
const handleModelFileLists = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.projectLogFileList = [];
      result.forEach((item)=>{
        form.projectLogFileList.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.projectLogFileList.splice(result, 1);
  }
};

const disabled = ref(true);
// 2.控制表单项是否只读
const isDisabled = () => {
  if (
    route.query.name === "3" ||
    route.query.name === "6" ||
    route.query.name === "5"
  ) {
    return (disabled.value = true);
  } else {
    return (disabled.value = false);
  }
};

let id;


const tgsubmitForm = async (formEl,t)=>{
  // if (route.query.id) {
  //   form.id = route.query.id;
  // }
  let paramsObj = {};
  if(t == "1"){
    //state: "1", 通过
    // let ctime = new Date();
    // var year = ctime.getFullYear();  // 年份
    // var month = ctime.getMonth() + 1;  // 月份，返回值为0-11，所以需要加1
    // var day = ctime.getDate(); 
    // // 对月份和日期进行补零
    // month = month < 10 ? '0' + month : month.toString();
    // day = day < 10 ? '0' + day : day.toString();
    // requestPayload.createTime = year + "-" + month + "-" + day;
    paramsObj = {
      checkOpinion: form.approvalOpinions, 
      id: dataCheckInfo.processCheckHistoryId, 
      dataId: form.logId, 
      copyFor: [], 
      keepCheckId: [], 
      state: "1", 
      fileList: form.approvalFile, 
      keepCheck: form.keepCheck,
      checkName: route.query.projectName,
      processTypeld:"16",
      processType : "项目日志审批"
    }
  }
  else{
    //state: "0",  驳回
    paramsObj = {
      checkOpinion: form.approvalOpinions, 
      id: dataCheckInfo.processCheckHistoryId, 
      dataId: form.logId, 
      copyFor: [], 
      keepCheckId: [], 
      state: "0", 
      fileList: form.approvalFile, 
      keepCheck: form.keepCheck,
      checkName: route.query.projectName,
      processTypeld:"16",
      processType : "项目日志审批"
    }
  }
  
   const response = await statusByProjectApi(paramsObj);
  if (response.code === 200) {
    // 添加成功的提示
    ElMessage.success(response.msg);
    // 2.跳转到对应的tab栏的列表，返回上一步
    router.back();
  } else {
    ElMessage.error(response.msg);
  }
}


// 确认填写日报
const submitForm = async (formEl) => {
  // if (route.query.id) {
  //   form.id = route.query.id;
  // }
  form.logId = id;

  let newArray = [];
  let userCcIds;
  let userIds;
  let requestPayload;
  // 编辑默认回显的时候 审批人
  if (form.processCheckBo.checkPeopleIds) {
    userIds = form.processCheckBo.checkPeopleIds.map((item) =>
      item.userId ? Number(item.userId) : item
    );
  }
  if (form.processCheckBo.copyFor) {
    userCcIds = form.processCheckBo.copyFor.map((item) =>
      item.userId ? Number(item.userId) : item
    );
  }
  if (form.processCheckBo.checkType === 1) {
    newArray = form.processCheckBo.checkPeopleIds.map((item, index) => {
      return {
        orderNum: index + 1,
        userId: item.userId ? Number(item?.userId) : item,
      };
    });

    requestPayload = {
      ...form,
      projectName:route.query.projectName,
      processCheckBo: {
        orderCheckPeopleInfoList: newArray, // 直接作为顶层属性
        copyFor: userCcIds, // 直接作为顶层属性
        checkType: form.processCheckBo.checkType,
        checkName: route.query.projectName,
        processTypeld:"16",
        datald: String(form.logId),
        projectId:form.projectId
      },
    };
  } else {
    requestPayload = {
      ...form,
      projectName:route.query.projectName,
      processCheckBo: {
        checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
        copyFor: userCcIds,
        checkType: form.processCheckBo.checkType,
        checkName: route.query.projectName,
        processTypeld:"16",
        datald: String(form.logId),
        projectId:form.projectId
      },
    };
  }

  const response = await updateNoticeApi(requestPayload);
  
  if (response.code === 200) {
    // 添加成功的提示
    ElMessage.success(response.msg);
    // 2.跳转到对应的tab栏的列表，返回上一步
    router.back();
  } else {
    ElMessage.error(response.msg);
  }
};

// 详情
const handelDetails = async () => {
  const response = await noticeDetailsList(route.query.id);
  if (response.code === 200 && response.data) {
    for (let key in form) {
      if (response.data[key]) {
        form[key] = response.data[key];
      }
    }
    id = response.data.logId;
    // 审批进度列表
    dataCheckInfo = response.data.dataCheckInfo;
    activities.value = response.data.dataCheckInfo && response.data.dataCheckInfo.opinons;

    form.approvalOpinions = dataCheckInfo.myCheckOpinionBo.opinion;
    if(dataCheckInfo.myCheckOpinionBo.fileList == null){
      form.approvalFile = [];
    }
    else{
      form.approvalFile = dataCheckInfo.myCheckOpinionBo.fileList;
    }
  }
};

onMounted(async () => {
  // await handelDetails();
    await handelDetails();
  // if (route.query.time || route.query.state) {
  //   time.value = route.query.time;
  //   status.value = route.query.state;
  //   // console.log(status.value);
  // }
});
</script>
<style lang="scss" scoped>
.concent {
  margin-top: 10px;
  .concent-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: 40px;
    h5 {
      font-weight: bold;
    }
  }
}
</style>
